package com.crawler.actor

import akka.actor.{Actor, ActorLogging}
import com.crawler.message.TaskParamListMessage
import com.crawler.service.DBService

/**
  * Created by tongtao.zhu on 2016/11/24.
  */
class CollectionActor extends Actor with ActorLogging{
  val dbService = DBService.dbService

  override def postStop(): Unit = {
    log.info("结束一个collectionActor")
  }

  override def preStart(): Unit = {
    // 订阅集群事件
    log.info("开始一个collectionActor")
  }

  override def receive = {
    case dbName: String =>{
      log.info("开始分配task...")
      val tasks = dbService.findTasks(dbName)
      val runningTasks = dbService.findRunningTask(dbName)
      val routerRef = context.actorSelection("/user/routerRef")
      if (tasks.length == 0 && runningTasks==0){
        log.info("所有的任务已经结束")
        sender() ! true
      }
      if (tasks.length > 0){
        routerRef ! tasks
      }
      sender() ! false
    }
    case TaskParamListMessage(tasks) => {
      dbService.createOrUpdate(tasks)
    }
    case _ => log.info("up")
  }
}
